package com.yufei.infoExtractor.util;

import java.io.File;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.CollectionUtils;


import com.yufei.infoExtractor.core.LinkAction;
import com.yufei.infoExtractor.core.LinkActionForPagination;
import com.yufei.infoExtractor.extractor.ContentExtractor;
import com.yufei.infoExtractor.extractor.UrlExtractor;
import com.yufei.infoExtractor.pfw.entity.PaginationRule;
import com.yufei.infoExtractor.pfw.entity.PropertyMatch;

public class PatternUtils {
	public static Log mLog = LogFactory.getLog(PatternUtils.class);

	/**
	 * @return link:表示需要判断类型的链接地址（完整的URL地址） 判定链接类别 -1表示未知类型
	 */
	public static Integer judgeLinkType(Map context, String link) {
		Map<String, String> regexMap = (Map<String, String>) context
				.get("regexMap");

		String linkTypeEntity = regexMap.get(String
				.valueOf(LinkAction.LINKTYPE_ENTITY)), linkTypeLinks = regexMap
				.get(String.valueOf(LinkAction.LINKTYPE_LINKS));

		Matcher matcher = null;
		List<String> results = null;
		if (linkTypeEntity != null) {

			results = PatternUtils.getListStrByRegex(link, linkTypeEntity);

			if (results.size() != 0) {
				return LinkAction.LINKTYPE_ENTITY;

			}
		}
		if (linkTypeLinks != null) {

			results = PatternUtils.getListStrByRegex(link, linkTypeLinks);
			if (results.size() != 0) {
				return LinkAction.LINKTYPE_LINKS;

			}
		}

		return LinkAction.LINKTYPE_UNKNOW;

	}

	/**用指定的一系列正则表达式对内容进行匹配，最总只返回一个匹配结果字符串
	 * @param content:要进行匹配的目标内容
	 * @param regexs：正则表达式，多个正则表达式之间以!号隔开
	 * @param isCleanHtml：是否对网页源码进行特殊的处理还是保留源码原样
	 * @return
	 */
	public static String getStrByRegex(String content, String regexs,
			boolean isCleanHtml) {
		String str = null;
		List<Pattern> patters = null;

		if (regexs == null) {
			return null;
		}

		Pattern pattern = null;
		String[] temps = null;
		List<Pattern> patterns = null;
		patterns = new ArrayList();
		temps = regexs.split("!");
		for (String reg : temps) {
			pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
			patterns.add(pattern);
		}
		str = PatternUtils.getStrByPattern(patterns, content);
		if (isCleanHtml) {
			str = CommonUtil.cleanHtml(str);
		}
		return str;

	}

	public static String getStrByRegex(String content, String regexs,
			int position) {
		String str = null;
		List<Pattern> patters = null;

		if (regexs == null) {
			return null;
		}

		Pattern pattern = null;
		String[] temps = null;
		List<Pattern> patterns = null;
		patterns = new ArrayList();
		temps = regexs.split("!");
		for (String reg : temps) {
			pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
			patterns.add(pattern);
		}
		str = PatternUtils.getStrByPattern(patterns, content, position);
		return str;

	}

	public static List<String> getListStrByRegex(String content, String regexs) {
		List<String> strs = null;
		List<Pattern> patters = null;

		if (regexs == null) {
			return null;
		}

		Pattern pattern = null;
		String[] temps = null;
		List<Pattern> patterns = null;
		patterns = new ArrayList();
		temps = regexs.split("!");
		for (String reg : temps) {
			pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
			patterns.add(pattern);
		}
		strs = PatternUtils.getListStrByPattern(patterns, content);
		return strs;

	}

	public static String getStrByRegex(Map<String, String> regexMap,
			String content, String property) {
		String str = null;
		List<Pattern> patters = null;
		String regexs = regexMap.get(property);
		if (regexs == null) {
			return null;
		}
		// 最用户配置的规则进行解析
		if (regexs.contains(";")) {
			String[] rules = regexs.split(";");
			content = PatternUtils.getStrByRegex(content, rules[0], false);
			str = PatternUtils.getStrByRegex(content, rules[1],
					(int) Integer.valueOf(rules[2]));

			return str;
		}
		str=PatternUtils.getStrByRegex(content, regexs, true);
		return str;

	}
	public static String getStrByRegex(PropertyMatch propertyMatch,
			String content, String property) {
		String str = null;
		List<Pattern> patters = null;
		String regexs = propertyMatch.getMatch();
		if (regexs == null) {
			return null;
		}
		// 最用户配置的规则进行解析
		if (regexs.contains(";")) {
			String[] rules = regexs.split(";");
			content = PatternUtils.getStrByRegex(content, rules[0], false);
			str = PatternUtils.getStrByRegex(content, rules[1],
					(int) Integer.valueOf(rules[2]));

			return str;
		}
		str=PatternUtils.getStrByRegex(content, regexs, true);
		return str;

	}
	/**
	 * @param patterns
	 *            (里面只有一组)
	 * @param content
	 * @return 根据正则表达式和要匹配的内容匹配出字符串
	 */
	public static String getStrByPattern(List<Pattern> patterns, String content) {

		String str = null;
		if (patterns == null || patterns.size() == 0) {
			mLog.debug("正则表达式没有配置,将匹配结果设置为为空字符串！");

			return "";
		}

		// pattern=Pattern.compile("精彩15优惠套餐([\r\n|\\d|\\w|\\D]{0,}(\r\n){0,})下一条",
		// Pattern.CASE_INSENSITIVE);
		int conti = 0;
		for (Pattern pattern : patterns) {
			if (conti == 1) {
				break;
			}
			Matcher matcher = pattern.matcher(content);
			// 假定正则表达式至少有一组
			int count = 0;

			while (matcher.find()) {
				count = matcher.groupCount();
				if (count == 0) {
					str = matcher.group(0);
				} else {
					str = matcher.group(1);

				}
				conti = 1;
			}
			if (str == null || str.equals("")) {
				str = "";
				mLog.debug("正则表达式匹配失败，正则表达式类型为：" + pattern.pattern()
						+ "将匹配结果设置为为空字符串！");

				// mLog.debug("匹配失败的内容是："+content);
				mLog.debug("*********************************************************************************");

			}
		}
		return str;
	}

	/**
	 * @param patterns
	 * @param content
	 * @param position
	 *            :指定位置的字符串
	 * @return
	 */
	public static String getStrByPattern(List<Pattern> patterns,
			String content, int position) {

		String str = null;
		if (patterns == null || patterns.size() == 0) {
			mLog.debug("正则表达式没有配置,将匹配结果设置为为空字符串！");

			return "";
		}

		int conti = 0;
		for (Pattern pattern : patterns) {
			if (conti == 1) {
				break;
			}
			Matcher matcher = pattern.matcher(content);
			// 假定正则表达式至少有一组
			int count = 0;
			int po = 1;
			// 匹配到的字符串数组循环
			while (matcher.find()) {
				count = matcher.groupCount();
				if (count == 0) {
					str = matcher.group(0);
				} else {
					if (po == position) {
						str = matcher.group(1);

					}

				}
				po += 1;
				conti = 1;
			}
			if (str == null || str.equals("")) {
				str = "";
				mLog.debug("正则表达式匹配失败，正则表达式类型为：" + pattern.pattern()
						+ "将匹配结果设置为为空字符串！");

				// mLog.debug("匹配失败的内容是："+content);
				mLog.debug("*********************************************************************************");

			}
		}
		return str;
	}

	public static List<String> getListStrByPattern(List<Pattern> patterns,
			String content) {
		List<String> strs = new ArrayList();
		;
		String str;
		if (patterns == null || patterns.size() == 0) {
			mLog.debug("正则表达式没有配置,将匹配结果设置为为空字符串！");

			return strs;
		}
		int conti = 0;
		for (Pattern pattern : patterns) {
			if (conti == 1) {
				break;
			}
			Matcher matcher = pattern.matcher(content);
			// 假定正则表达式至少有一组
			int count = 0;
			String matchContent = null;
			while (matcher.find()) {
				count = matcher.groupCount();

				for (int i = 0; i < count; i++) {
					matchContent = matcher.group(i + 1);
					addUniqueElement(strs, matchContent);
					// strs.add();

				}
				if (count == 0) {
					matchContent = matcher.group(0);

					addUniqueElement(strs, matchContent);
				}

				conti = 1;
			}

		}
		if (strs.size() == 0) {
			for (Pattern pattern : patterns) {
				mLog.debug("正则表达式匹配失败，正则表达式类型为：" + pattern.pattern());
			}
			// mLog.debug("匹配失败的内容是："+content);
			mLog.debug("*********************************************************************************");

		}
		return strs;
	}

	public static void addUniqueElement(List list, Object obj) {
		if (!list.contains(obj)) {
			list.add(obj);

		}

	}




	public static void main(String[] args) {
		String str = "<DIV class=breadcrumb><STRONG><A href=\"http://www.360buy.com/computer.html\" jQuery1346256415554=\"185\">电脑、办公</A></STRONG><SPAN>&nbsp;&gt;&nbsp;<A href=\"http://www.360buy.com/products/670-671-000.html\" jQuery1346256415554=\"186\">电脑整机</A>&nbsp;&gt;&nbsp;<A href=\"http://www.360buy.com/products/670-671-672.html\" jQuery1346256415554=\"187\">笔记本</A>&nbsp;&gt;&nbsp;<A href=\"http://www.360buy.com/brands/672-319.html\" jQuery1346256415554=\"188\">富士通</A>&nbsp;&gt;&nbsp;<A href=\"http://www.360buy.com/product/577376.html\" jQuery1346256415554=\"189\">富士通LH531</A></SPAN> </DIV></DIV><!--crumb end-->";
		str = CommonUtil.getStringFromFile(new File(
				"src/test/resources/html/links.html"));

		/*
		 * List<Pattern> patterns=new ArrayList<Pattern>();
		 * patterns.add(Pattern.compile("<A[\\s]{1,}.*?>(.*?)</A>"));
		 * System.out.print(PatternUtils.getStrByPattern(patterns, str, 3));
		 */
		Map<String, String> regexMap = new HashMap<String, String>();
		regexMap.put("category", "breadcrumb.*;<A[\\s]{1,}.*?>(.*?)</A>;3");
		System.out.print(PatternUtils.getStrByRegex(regexMap, str, "category"));
		PaginationRule paginationRule=null;
		System.out.print(paginationRule==null?"":paginationRule.toString());
		}
}
